package com.drawu.drawuspring.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.drawu.drawuspring.constants.CommonConstants;
import com.drawu.drawuspring.domain.DTO.CommentDTO;
import com.drawu.drawuspring.domain.DTO.MessageDto;
import com.drawu.drawuspring.domain.DTO.PostDTO;
import com.drawu.drawuspring.domain.Result;
import com.drawu.drawuspring.domain.VO.CommentVO;
import com.drawu.drawuspring.domain.VO.PostVO;
import com.drawu.drawuspring.domain.VO.UserVO;
import com.drawu.drawuspring.domain.po.*;
import com.drawu.drawuspring.enums.AppHttpCodeEnum;
import com.drawu.drawuspring.mapper.*;
import com.drawu.drawuspring.service.ICommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.drawu.drawuspring.service.IImagesService;
import com.drawu.drawuspring.service.IUsersService;
import com.drawu.drawuspring.service.IForumService;
import com.drawu.drawuspring.utils.AppThreadLocalUtil;
import com.drawu.drawuspring.utils.BeanUtils;
import com.drawu.drawuspring.utils.CollUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

import static com.drawu.drawuspring.utils.Coze.runWorkflow1;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author hui
 * @since 2024-10-14
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments> implements ICommentsService {

    private final IUsersService usersService;
    private final MessageMapper messageMapper;
    public final ForumMapper forumMapper;
    public final ImagesMapper imagesMapper;
    public final GameInfoMapper gameInfoMapper;
    public final IImagesService iImagesService;

    /**
     * 添加评论
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addComment(CommentDTO dto) {
        //获取当前用户id
        Users user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto.getPostId() == null){
            return Result.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Comments comments = BeanUtils.copyBean(dto, Comments.class);

        comments.setUserId(user.getId());
        boolean success = this.save(comments);
        if (success) {
            MessageDto messageDto = new MessageDto();
            messageDto.setUserId(user.getId());
            messageDto.setTargetId(comments.getReceiverId());
            messageDto.setSourceId(comments.getPostId());
            messageDto.setContent(comments.getContent());
            // 帖子评论
            if (comments.getType() == 0) {
                messageDto.setType("postComment");
                Posts post = forumMapper.selectById(comments.getPostId());
                List<Images> urls = imagesMapper.selectList(new QueryWrapper<Images>().eq("posts_id", post.getId()));
                if (CollUtils.isEmpty(urls)) {
                    messageDto.setUrl(post.getTitle());
                } else {
                    messageDto.setUrl(urls.get(0).getUrl());
                }
                Message message = BeanUtils.copyBean(messageDto, Message.class);
                messageMapper.insert(message);
            } else if (comments.getType() == 1) {
                // 桌游评论
                messageDto.setType("gameComment");
                GameInfo gameInfo = gameInfoMapper.selectById(comments.getPostId());
                messageDto.setUrl(gameInfo.getPicture());
                Message message = BeanUtils.copyBean(messageDto, Message.class);
                messageMapper.insert(message);
            }
            return Result.success(CommonConstants.COMMENT_SUCCESS);
        } else {
            return Result.fail(CommonConstants.COMMENT_FAILED);
        }
    }

    /**
     * 根据postId获取评论数量
     *
     */
    @Override
    public Integer getCommentCountByPostId(Integer postId) {
        Long count = this.lambdaQuery().eq(Comments::getPostId, postId).count();
        return count.intValue();
    }

    @Override
    public Result replyComment(PostDTO dto) throws Exception {
        String key = "标题:" + dto.getTitle() + "\n内容:" + dto.getContent();
        JSONObject jsonObject = runWorkflow1(key, "7486059684798218251");
        String answer = jsonObject.getString("output");
        CommentDTO commentDTO = new CommentDTO();
        commentDTO.setPostId(dto.getPostId());
        commentDTO.setContent(answer);
        //获取当前用户id
        if (dto.getPostId() == null){
            return Result.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Comments comments = BeanUtils.copyBean(commentDTO, Comments.class);
        log.info("评论内容：{}", comments);
        if (comments.getRepliedCommentId()!=null&&comments.getRepliedCommentId()!=0){
            comments.setFatherId(comments.getRepliedCommentId());
        }
        // 机器人ID为39
        comments.setUserId(39);
        boolean success = this.save(comments);
        if (success) {
            MessageDto messageDto = new MessageDto();
            messageDto.setUserId(39);
            messageDto.setTargetId(comments.getReceiverId());
            messageDto.setSourceId(comments.getPostId());
            messageDto.setContent(comments.getContent());
            // 帖子评论
            messageDto.setType("postComment");

            List<Images> urls = imagesMapper.selectList(new QueryWrapper<Images>().eq("posts_id", dto.getPostId()));
            if (CollUtils.isEmpty(urls)) {
                messageDto.setUrl(dto.getTitle());
            } else {
                messageDto.setUrl(urls.get(0).getUrl());
            }
            Message message = BeanUtils.copyBean(messageDto, Message.class);
            messageMapper.insert(message);
            return Result.success(CommonConstants.COMMENT_SUCCESS);
        } else {
            return Result.fail(CommonConstants.COMMENT_FAILED);
        }
    }

    @Override
    public Result deleteComment(Integer postId, Integer commentId) {
        // 判断删除权限
        Users user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Comments comments = this.getById(commentId);
        if (comments == null) {
            return Result.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (user.getId() != comments.getUserId()) {
            return Result.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        boolean success = this.removeById(commentId);
        if (success) {
            return Result.success();   //删除成功
        }
        return null;
    }

    public Result uploadImage(MultipartFile mpFile) {
        String url = iImagesService.uploadImage(mpFile,"comments");
        return Result.success(url);
    }

    /**
     * 根据postId获取评论列表
     *
     */
    @Override
    public List<CommentVO> getCommentsByPostId(Integer type, Integer postId) {
        List<Comments> fatherCommentsList = this.lambdaQuery()
                .eq(Comments::getType, type)
                .eq(Comments::getPostId, postId)
                .eq(Comments::getFatherId, 0)
                .orderByDesc(Comments::getCreateTime)
                .list();
        List<Integer> userIds = fatherCommentsList.stream().map(Comments::getUserId).filter(Objects::nonNull).collect(Collectors.toList());
        if (userIds.isEmpty()){
            return null;
        }
        List<UserVO> userVoList = BeanUtils.copyList(usersService.listByIds(userIds), UserVO.class);
        Map<Integer, UserVO> userVOMap = userVoList.stream().collect(Collectors.toMap(UserVO::getId, userVo -> userVo));
        List<CommentVO> fatherCommentVOList = BeanUtils.copyList(fatherCommentsList, CommentVO.class);
        for (CommentVO commentVO : fatherCommentVOList) {
            List<Comments> childCommentsList = this.lambdaQuery()
                    .eq(Comments::getPostId, postId)
                    .eq(Comments::getFatherId, commentVO.getId())
                    .orderByAsc(Comments::getCreateTime)
                    .list();
            List<CommentVO> childCommentVOList = BeanUtils.copyList(childCommentsList, CommentVO.class);
            List<Integer> childUserIds = childCommentVOList.stream().map(CommentVO::getUserId).filter(Objects::nonNull).collect(Collectors.toList());
            List<UserVO> childUserVOList = new ArrayList<>();
            if ( !childUserIds.isEmpty()){
                childUserVOList = BeanUtils.copyList(usersService.listByIds(childUserIds), UserVO.class);
            }
            Map<Integer, UserVO> childUserVOMap = childUserVOList.stream().collect(Collectors.toMap(UserVO::getId, userVo -> userVo));
            for (CommentVO childCommentVO : childCommentVOList) {
                childCommentVO.setUserVO(childUserVOMap.get(childCommentVO.getUserId()));
            }
            commentVO.setUserVO(userVOMap.get(commentVO.getUserId()));
            commentVO.setChildren(childCommentVOList);

        }
        return fatherCommentVOList;
    }

}
